package com.xiaoq.matrix.activity.endpoint;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.apis.user.IUserApi;
import com.xiaoq.apis.user.UserInfo4SocialVo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.matrix.activity.entity.ActivityAttendentEntity;
import com.xiaoq.matrix.activity.entity.ActivityEntity;
import com.xiaoq.matrix.activity.service.IActivityAttendService;
import com.xiaoq.matrix.activity.service.IActivityService;
import com.xiaoq.matrix.activity.vo.ActivityAttendVo;
import com.xiaoq.matrix.activity.vo.ActivityViewVo;
import com.xiaoq.matrix.activity.vo.ActivityVo;
import com.xiaoq.matrix.vo.Activity4TermVo;
import com.xiaoq.vo.PagingVo;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping("/api/v1/activity")
public class ActivityEndpoint2C {

	@Autowired
	private IActivityAttendService activityAttendSer;
	
	@Reference(interfaceClass=IUserApi.class, check=false, version="1.0.0")
	private IUserApi userDubboApi;

	@Autowired
	private IActivityService activitySer;

	private static final Logger LOG = LoggerFactory.getLogger(ActivityEndpoint2C.class);

	private class UserActivityAttendList extends GenericListResponse<ActivityAttendVo> {
	}

	private class ActivityViewListResponse extends GenericListResponse<ActivityViewVo> {
	}

	private class Activity4TermListResponse extends GenericListResponse<Activity4TermVo> {
	};

	private class ActivityDetailResponse extends GenericDataResponse<ActivityVo> {
	}
	
	private class ActivityAttendStatusResponse extends GenericDataResponse<Boolean>{}
	
	private class ActivityShareNum extends GenericDataResponse<Integer> {}

	@ApiOperation(value = "小程序返回景区活动列表", notes = "小程序返回景区活动列表")
	@ApiResponses({ @ApiResponse(code = 200, response = ActivityViewListResponse.class, message = "小程序返回景区活动列表") })
	@GetMapping(value = "/4miniPro", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> findActivityByOrgnizerId(
			@RequestParam(value = "orgnizerId", required = true)@ApiParam(value="景区Id",required = true) String orgnizerId,
			@ModelAttribute(value = "pvo") PagingVo pvo) {
		List<ActivityEntity> activityList = activitySer.findActivityListByOrgnizer(orgnizerId, null, null, null,
				"20",pvo);
		Long total = (Long) pvo.getTc();

		List<ActivityViewVo> activityViewVoList = new ArrayList<>();
		ActivityViewVo activityViewVo = null;
		if (activityList != null) {
			for (ActivityEntity activity : activityList) {
				activityViewVo = new ActivityViewVo();
				BeanUtils.copyProperties(activity, activityViewVo);
				activityViewVoList.add(activityViewVo);
				List<ActivityAttendentEntity> activityAttendList = activityAttendSer
						.findActivityAttendByAct(activity.getId());
				Long attendNums = 0L;
				if (activityAttendList != null) {
					for (ActivityAttendentEntity activityAttend : activityAttendList) {
						attendNums = attendNums + activityAttend.getUserCount();
					}

				}
				activityViewVo.setAttendNums(attendNums);
			}
		}
		if(total==null){
			total=0L;
		}
		return ActivityViewListResponse.listAndCount(activityViewVoList, total);

	}
	
	@ApiOperation(value = "活动分享量统计", notes = "活动分享量统计")
	@ApiResponses({ @ApiResponse(code = 200, response = ActivityShareNum.class, message = "活动分享量统计") })
	@PutMapping(value = "/shareNum", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> shareNum(@RequestParam(value = "activityId", required = true) String activityId){
		ActivityEntity activity = activitySer.findActivity2C(activityId);
		Integer shareNum = activity.getShareNum();
		if(shareNum==null){
			shareNum=0;
		}
		shareNum = shareNum+1;
		activity.setShareNum(shareNum);
		activitySer.addActivity(activity);
		return ActivityShareNum.okWithData(shareNum);
		
	}
	
	@ApiOperation(value = "获取活动列表（首页）", notes = "获取活动列表（首页）")
	@ApiResponses({ @ApiResponse(code = 200, response = Activity4TermListResponse.class, message = "活动列表") })
	@GetMapping(value = "/{userId}/4homepage", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> activityList(
			@PathVariable(name = "userId", required = false) @ApiParam(value = "用户Id", required = false) String userId,
			@RequestParam(name = "city", required = false) @ApiParam(value = "城市code", required = true) String city,
			@RequestParam(name = "lng", required = false) @ApiParam(value = "经度", required = false) Double lng,
			@RequestParam(name = "lat", required = false) @ApiParam(value = "纬度", required = false) Double lat,
			@ModelAttribute(value = "pvo") PagingVo pvo) {
		// 初期实现为和第三个tab的活动数据是一样的

		List<ActivityEntity> activityList = activitySer.findActivityListByCity2C(city,null, pvo);

		Long total = (Long) pvo.getTc();

		List<Activity4TermVo> activity4TermList = new ArrayList<>();
		Activity4TermVo activity4TermVo = null;
		if (activityList != null) {
			for (ActivityEntity activity : activityList) {
				activity4TermVo = new Activity4TermVo();
				BeanUtils.copyProperties(activity, activity4TermVo);
				activity4TermList.add(activity4TermVo);
			}
		}
		if(total==null){
			total = 0L;
		}
		return Activity4TermListResponse.listAndCount(activity4TermList, total);
	}

	@ApiOperation(value = "获取活动列表（发现页）", notes = "获取活动列表（发现页）")
	@ApiResponses({ @ApiResponse(code = 200, response = ActivityViewListResponse.class, message = "活动列表") })
	@GetMapping(value = "/4foundpage", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> findActivityByCity(
			@RequestParam(value = "city", required = false) @ApiParam(value = "城市code", required = false) String city,
			@RequestParam(value = "district", required = false) @ApiParam(value = "区县编码", required = false) String district,
			@ModelAttribute(value = "pvo") PagingVo pvo) {
		List<ActivityEntity> activityList = activitySer.findActivityListByCity2C(city,district, pvo);

		Long total = (Long) pvo.getTc();

		List<ActivityViewVo> activityViewVoList = new ArrayList<>();
		ActivityViewVo activityViewVo = null;
		if (activityList != null) {
			for (ActivityEntity activity : activityList) {
				activityViewVo = new ActivityViewVo();
				BeanUtils.copyProperties(activity, activityViewVo);
				activityViewVoList.add(activityViewVo);
				List<ActivityAttendentEntity> activityAttendList = activityAttendSer
						.findActivityAttendByAct(activity.getId());
				Long attendNums = 0L;
				if (activityAttendList != null) {
					for (ActivityAttendentEntity activityAttend : activityAttendList) {
						attendNums = attendNums + activityAttend.getUserCount();
					}

				}
				activityViewVo.setAttendNums(attendNums);
			}
		}
		if(total==null){
			total=0L;
		}
		return ActivityViewListResponse.listAndCount(activityViewVoList, total);

	}

	@ApiOperation(value = "获取活动详情", notes = "获取活动详情")
	@ApiResponses({ @ApiResponse(code = 200, response = ActivityDetailResponse.class, message = "获取活动详情") })
	@GetMapping(value = "/{id}/detail", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> findActivityDetail(@PathVariable(value = "id", required = true) String id) {
		ActivityEntity activity = activitySer.findActivity2C(id);
		if(activity==null){
			return GenericResponse.ng("您查找的活动正在审核之中！");
		}
		String activityId = activity.getId();
		{
			ActivityVo activityVo = new ActivityVo();
			BeanUtils.copyProperties(activity, activityVo);
			List<ActivityAttendentEntity> activityAttendList = activityAttendSer
					.findActivityAttendByAct(activity.getId());
			Long attendNums = 0L;
			if (activityAttendList != null) {
				for (ActivityAttendentEntity activityAttend : activityAttendList) {
					attendNums = attendNums + activityAttend.getUserCount();
				}
			}

			activityVo.setAttendNums(attendNums);
			String sharingUrl = "https://www.xiaoq.online/activity/activeDetail.html?id="+activityId;
			activityVo.setSharingUrl(sharingUrl);
			Integer shareNum = activityVo.getShareNum();
			if(shareNum==null){
				activityVo.setShareNum(0);
			}
			return ActivityDetailResponse.okWithData(activityVo);
		}
	}

	@ApiOperation(value = "分享静态页面访问的活动详情", notes = "分享静态页面访问的活动详情")
	@ApiResponses({ @ApiResponse(code = 200, response = ActivityDetailResponse.class, message = "分享静态页面访问的活动详情") })
	@GetMapping(value = "/detail", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> shareActivityDetail(@RequestParam(value="id",required=true)@ApiParam(value="活动Id",required=true)String id) {
		ActivityEntity activity = activitySer.findActivity2C(id);
		if (activity != null) {
			ActivityVo activityVo = new ActivityVo();
			BeanUtils.copyProperties(activity, activityVo);
			List<ActivityAttendentEntity> activityAttendList = activityAttendSer
					.findActivityAttendByAct(activity.getId());
			Long attendNums = 0L;
			if (activityAttendList != null) {
				for (ActivityAttendentEntity activityAttend : activityAttendList) {
					attendNums = attendNums + activityAttend.getUserCount();
				}
			}

			activityVo.setAttendNums(attendNums);
			return ActivityDetailResponse.okWithData(activityVo);
		}
		LOG.debug("查询结果为空！");
		return GenericResponse.ng("查询该活动失败！");
	}
	

	@ApiOperation(value = "获取用户的活动报名列表", notes = "获取用户的活动报名列表")
	@ApiResponses({ @ApiResponse(code = 200, response = UserActivityAttendList.class, message = "用户的活动报名列表") })
	@GetMapping(value = "/attend/{userId}/ofuser", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getUserActivityAttend(@PathVariable(value = "userId", required = false)@ApiParam(value="userId",required=false)String userId,
			@ModelAttribute(value = "pvo") PagingVo pvo) {

		if (StringUtils.isNotEmpty(userId)) {
			List<ActivityAttendentEntity> activityAttendList = activityAttendSer.findActivityAttendByUser(userId, pvo);
			List<ActivityAttendVo> activityAttendVoList = new ArrayList<>();
			ActivityAttendVo activityAttendVo = null;
			if (activityAttendList != null) {
				for (ActivityAttendentEntity activityAttend : activityAttendList) {
					activityAttendVo = new ActivityAttendVo();
					String activityId = activityAttend.getActivityId();
					ActivityEntity activity = activitySer.findActivity2C(activityId);
					BeanUtils.copyProperties(activity, activityAttendVo);
					BeanUtils.copyProperties(activityAttend, activityAttendVo);
					
					List<ActivityAttendentEntity> activityAttendList2 = activityAttendSer
							.findActivityAttendByAct(activityId);
					Long attendNums = 0L;
					if (activityAttendList2 != null) {
						for (ActivityAttendentEntity activityAttend2 : activityAttendList2) {
							attendNums = attendNums + activityAttend2.getUserCount();
						}
					}
					activityAttendVo.setUserCount(attendNums.intValue());
					
					String activityTitle = activity.getTitle();
					activityAttendVo.setActivityTitle(activityTitle);
					activityAttendVoList.add(activityAttendVo);
				}
			}

			Long total = (Long) pvo.getTc();
			if(total==null){
				total=0L;
			}
			return UserActivityAttendList.listAndCount(activityAttendVoList, total);

		}
		LOG.debug("userId 参数不应该为空！");
		return GenericResponse.ng("查询失败,请重新操作");
	}
	
	@ApiOperation(value = "添加活动报名信息", notes = "添加活动报名信息")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "活动报名信息") })
	@PostMapping(value = "/{userId}/attend", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addActivityAttend(
			@PathVariable(value="userId",required=false)@ApiParam(value="userId",required=false)String userId,
			@ModelAttribute(value = "activityAttendVo") ActivityAttendVo activityAttendVo) {
		if(StringUtils.isNotEmpty(userId)){
			
			UserInfo4SocialVo userInfo = userDubboApi.getUserInfo4Social(userId);
			userId = userInfo.getId();
			if(StringUtils.isNotEmpty(userId)){
				String userNickName = userInfo.getNickName();
				String userLogo = userInfo.getLogoUrl();
				activityAttendVo.setUserId(userId);
				activityAttendVo.setUserNickName(userNickName);
				activityAttendVo.setUserLogo(userLogo);
				LOG.info(" activityAttendVo:"+activityAttendVo);
				Integer userCount = activityAttendVo.getUserCount();
				if(userCount==null||userCount==0){
					return GenericResponse.ng("报名人数不能为0！");
				}
				String activityId = activityAttendVo.getActivityId();
				Integer remainNums = 0;
				Integer maxParticipants = 0;
				Long attendNums = 0L;
				attendNums = activityAttendSer.getAttendNums(activityId);
				if (StringUtils.isNotEmpty(activityId)) {
					ActivityEntity activity = activitySer.findActivity2C(activityId);
					if (activity != null) {
						maxParticipants = activity.getMaxParticipants();
					}

					remainNums = (int) (maxParticipants - attendNums);

				}
				//TODO  这里不能这么简单的处理,这里后期有一个线程安全的处理
				if (remainNums >= userCount) {
					ActivityAttendentEntity activityAttend = new ActivityAttendentEntity();
					BeanUtils.copyProperties(activityAttendVo, activityAttend);
					activityAttendSer.addActivityAttend(activityAttend);
					return GenericResponse.ok();
				} else {
					return GenericResponse.ng("您输入的人数已超过本次活动的最多报名人数 请重新输入!");
				}
			}else{
				LOG.error("查不到这个userId对应的user信息");
				return GenericResponse.ng("请先注册！");
			}
			
			
		}else{
			return GenericResponse.ng("请先登录！");
		}
		

	}
	
	@ApiOperation(value = "查看用户是否已经报名", notes = "查看用户是否已经报名")
	@ApiResponses({ @ApiResponse(code = 200, response = ActivityAttendStatusResponse.class, message = "查看用户是否已经报名") })
	@GetMapping(value = "/{userId}/attend", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getActivityAttendStatus(@PathVariable(value="userId",required=false)@ApiParam(value="userId",required=false)String userId,@RequestParam(value="activityId",required=true)@ApiParam(value="activityId",required=true)String activityId){
		boolean result = activityAttendSer.isUserAttend(userId, activityId);
		if(result){
			return ActivityAttendStatusResponse.okWithData(true);
		}
		
		return ActivityAttendStatusResponse.okWithData(false);
	}

	
}
